package controller

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Json"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Reflect"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Slice"
	"gitee.com/fierce_wolf/go-fox-edge-common/httpserver"
	"go-fox-edge-kernel-manager/utils/PageUtils"
	"strings"
)

type consoleManageController struct {
}

func (e *consoleManageController) init() {
	httpserver.Server.POST("/console/page", e.selectPageList)
}

func (e *consoleManageController) selectPageList(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	// 提取业务参数
	serviceType := Map.GetString(body, "serviceType", "")
	serviceName := Map.GetString(body, "serviceName", "")
	level := Map.GetString(body, "level", "")
	pageNum := Map.GetInt(body, "pageNum", 1)
	pageSize := Map.GetInt(body, "pageSize", 10)

	// 简单校验参数
	if Map.HasNull(body, "pageNum", "pageSize") {
		return nil, errors.New("参数不能为空:pageNum, pageSize")
	}

	// 只要用户填写了过滤参数：那么就将全部记录拿出来，然后手动筛选。
	if !Method.HasEmpty(serviceType) || !Method.HasEmpty(serviceName) || !Method.HasEmpty(level) {
		arr, err := commLogger.Console.GetAll()
		if err != nil {
			return nil, err
		}

		Slice.Reverse(arr)

		list := make([]map[string]interface{}, 0)
		for _, object := range arr {
			if !Method.HasEmpty(serviceType) && !e.like(object, "serviceType", serviceType) {
				continue
			}
			if !Method.HasEmpty(serviceName) && !e.like(object, "serviceName", serviceName) {
				continue
			}
			if !Method.HasEmpty(level) && !e.like(object, "level", level) {
				continue
			}

			value := object["value"]
			if value != nil && !(Reflect.IsString(value)) {
				object["value"] = Json.BuildJson(value)
			}

			list = append(list, object)
		}

		data := PageUtils.GetMapPageList(list, pageNum, pageSize)
		return data, nil
	} else {
		// 用户没有填写过滤条件，那么直接在redis分页取数据
		total, err := commLogger.Console.Size()
		if err != nil {
			return nil, err
		}

		pageEndId := total - 1 - int64(pageSize)*int64(pageNum-1)
		pageStartId := total - int64(pageSize) - int64(pageSize)*int64(pageNum-1)
		if pageStartId < 0 {
			pageStartId = 0
		}

		list, err := commLogger.Console.GetRang(pageStartId, pageEndId)
		if err != nil {
			return nil, err
		}

		Slice.Reverse(list)

		data := make(map[string]interface{})
		data["list"] = list
		data["total"] = total
		return data, nil
	}
}

func (e *consoleManageController) like(mp map[string]interface{}, key string, value string) bool {
	if value == "" {
		return false
	}

	data := mp[key]
	if data == nil {
		return false
	}

	if Reflect.IsString(data) {
		return strings.Count(data.(string), value) > 0
	}

	return false
}
